java ElasticSearch并发操作之乐观锁的使用

ES在添加和更新操作,其实是不安全的,所有的数据库db系统都会存在并发问题像关系型数据库MySQL,Oracle,SQL Server默认采用的是悲观锁。

在ElasticSearch中采用的乐观锁,下面先熟悉下什么是乐观锁和悲观锁:

悲观锁(Pessimistic Lock), 顾名思义,就是很悲观,每次去拿数据的时候都认为别人会修改,所以每次在拿数据的时候都会上锁,这样别人想拿这个数据就会block直到它拿到锁。传统的关系型数据库里边就用到了很多这种锁机制,比如行锁,表锁等,读锁,写锁等,都是在做操作之前先上锁。

乐观锁(Optimistic Lock), 顾名思义,就是很乐观,每次去拿数据的时候都认为别人不会修改,所以不会上锁,但是在更新的时候会判断一下在此期间别人有没有去更新这个数据,可以使用版本号等机制。乐观锁适用于多读的应用类型,这样可以提高吞吐量,像数据库如果提供类似于write_condition机制的其实都是提供的乐观锁。

两种锁各有优缺点,不可认为一种好于另一种,像乐观锁适用于写比较少的情况下,即冲突真的很少发生的时候,这样可以省去了锁的开销,加大了系统的整个吞吐量。但如果经常产生冲突,上层应用会不断的进行retry,这样反倒是降低了性能,所以这种情况下用悲观锁就比较合适。

从上面的介绍中,我们不难发现es为什么要采用乐观锁,因为es大部分场景下都是一个读多写少的系统,如果按照悲观锁的策略,会大大降低es的吞吐,当然并发问题是真实存在

在java中插入中使用setCreate(true)方法,标记同一个时刻插入的数据,只会有一条数据插入成功, 在修改中,可以通过es内部维护的version字段来自定义实现灵活控制的乐观锁

java代码如下

/**
     * ES新增或修改同步方法
     *
     * @param index 索引
     * @param type  类型
     * @param id 文档
     * @param json 文档内容
     * @param thread 线程名称
     * @return
     */
    public static Map<String, Object> sync(String index, String type, String id, JSONObject json, String thread){
        GetResponse getResponse = get(index, type, id);
        Map map = getResponse.getSource();
        // 不存在
        if(null == map){
            // 新增
            try {
                IndexResponse response = client.prepareIndex(index, type, id).setCreate(true).setSource(json).execute().actionGet();
                LOGGER.info(thread + "新增文档成功,文档id为:" + response.getId() + ",状态为:" + response.status() );
            } catch (VersionConflictEngineException e) {
                //e.printStackTrace();
                LOGGER.info(thread + "插入失败" );
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    //e1.printStackTrace();
                }
                sync(index, type, id, json, thread);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            //修改
            try{
                long version = getResponse.getVersion();
                LOGGER.info("此时在修改中,当前版本:" + String.valueOf(version));

                client.prepareUpdate(index, type, id).setDoc(json).setVersion(version).execute().actionGet();

                Thread.sleep(100);
                GetResponse response = get(index, type, id);
                Map<String, Object> m = response.getSource();

                LOGGER.info(thread + "线程修改完成, 当前年龄为:"+m.get("age") );

            } catch (VersionConflictEngineException e) {
                //e.printStackTrace();
                LOGGER.info(thread + "修改失败,当前有线程在修改,休眠1秒后重试...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                sync(index, type, id, json, thread);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Map map1 = json.getInnerMap();
        return map1;
    }
/**
     * ES新增同步方法
     * @param index
     * @param type
     * @param id
     * @param json
     * @param thread
     */
    public static void  insert(String index, String type, String id, JSONObject json, String thread)  {
        try {
            IndexResponse response = client.prepareIndex(index, type, id).setCreate(true).setSource(json).execute().actionGet();
            LOGGER.info(thread + "新增文档成功,文档id为:" + response.getId() + ",状态为:" + response.status());
        } catch (VersionConflictEngineException e) {
            LOGGER.info("VersionConflictEngineException =================");
            e.printStackTrace();
            //update(index, type, id, json, thread);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
/**
     * ES修改同步方法
     *
     * @param index
     * @param type
     * @param id
     * @param json
     * @param thread
     */
    public static void update(String index, String type, String id, JSONObject json, String thread){
        try{
            // 修改
            GetResponse response = get(index, type, id);
            long version = response.getVersion();
            LOGGER.info("此时在修改中,当前版本:" + String.valueOf(version));

            client.prepareUpdate(index, type, id).setDoc(json).setVersion(version).execute().actionGet();

            Thread.sleep(100);
            response = get(index, type, id);
            Map<String, Object> m = response.getSourceAsMap();

            LOGGER.info(thread + "线程修改完成, 当前年龄为:"+m.get("age") );

        } catch (VersionConflictEngineException e) {
            e.printStackTrace();
            LOGGER.info(thread + "修改失败,当前有线程在修改,休眠3秒后重试...");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            update(index, type, id, json, thread);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
/**
     * 查询当前的记录
     *
     * @param index
     * @param type
     * @param id
     * @return
     */
    public static GetResponse get(String index, String type, String id){
        GetRequestBuilder getRequestBuilder = client.prepareGet(index, type, id);
        GetResponse getResponse = getRequestBuilder.execute().actionGet();
        LOGGER.info("查询当前文档版本为:" + String.valueOf(getResponse.getVersion()));

        return getResponse;
    }

参考:https://blog.csdn.net/m0_37557582/article/details/78928654

https://blog.csdn.net/y472360651/article/details/78287211

https://blog.csdn.net/u010454030/article/details/60969509

https://blog.csdn.net/u011262847/article/details/78118142?locationNum=9&fps=1

https://blog.csdn.net/R_P_J/article/details/78388783

https://blog.csdn.net/hellozhxy/article/details/79911259

https://blog.csdn.net/u010454030/article/details/60969509

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值